package com.epam.manager.backingbeans;

import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.inject.Inject;
import javax.transaction.UserTransaction;

import com.epam.DAO.BillDAO;
import com.epam.DAO.CarDAO;
import com.epam.entity.Bill;
import com.epam.entity.Car;
import com.epam.entity.Request;
import com.epam.entity.Status;
import com.epam.events.Notifications;
import com.epam.events.TypedAnnotationLiteral;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.enterprise.event.Event;

import org.apache.log4j.Logger;

public class ActiveRequestManagedBean extends RequestController {

	private DataModel<Bill> bills;
	private Request request;
	private Bill bill;

	@EJB
	private BillDAO billDAO;
	@EJB
	private CarDAO carDAO;
	@Inject
	private Event<Request> eventProcessor;
	@Resource
	private UserTransaction utx;
	private static Logger logger = Logger
			.getLogger(ActiveRequestManagedBean.class);

	public ActiveRequestManagedBean() {
		super();
		bills = new ListDataModel<Bill>();
	}

	public Bill getBill() {
		return bill;
	}

	public void setBill(Bill bill) {
		this.bill = bill;
	}

	public Request getRequest() {
		return request;
	}

	public void setRequest(Request request) {
		this.request = request;
	}

	public DataModel<Bill> getBills() {
		bills.setWrappedData(billDAO.getRequestBills(requests.getRowData()));
		return bills;
	}

	public void setBills(DataModel<Bill> bills) {
		this.bills = bills;
	}

	@Override
	public DataModel<Request> getRequests() {
		
		requests.setWrappedData(requestDAO.getRequests(firstRow, rowsPerPage,
				Status.ACTIVE));
		totalRows = requestDAO.getRequestsCount(Status.ACTIVE);
		// Set currentPage, totalPages and pages.
		currentPage = (totalRows / rowsPerPage)
				- ((totalRows - firstRow) / rowsPerPage) + 1;
		totalPages = (totalRows / rowsPerPage)
				+ ((totalRows % rowsPerPage != 0) ? 1 : 0);

		return requests;
	}

	public void initRequest() {
		request = requests.getRowData();
		bill = new Bill();
	}

	public void closeRequest() {
		try {
			try {
				utx.begin();

				request.setStatus(Status.CLOSED);
				requestDAO.update(request);

				Car car = request.getCar();
				car.setIsAvaliable(true);
				carDAO.update(car);

				eventProcessor.select(
						new TypedAnnotationLiteral(Notifications.CLOSED)).fire(
						request);

				utx.commit();
			} catch (Exception err) {
				utx.rollback();
			}
		} catch (Exception e) {
			logger.error(e.toString());
		}
	}

	public void makeAdditionalBill() {
		bill.setRequest(request);
		bill.setStatus(Status.NOT_PAYED);
		billDAO.create(bill);
	}

}
